<template>
	<Mask />
	<div id="create-wrap">
		<div class="score-content">
			<div class="score-header">
				<div class="face"><img :src="state.face" alt=""></div>
				<h4 class="name">{{ state.query.name }}</h4>
			</div>
			<div class="score-header-line">
				<span></span>
				<span></span>
			</div>
			<div class="score-wrap">
				<div>
					<div class="total-score">
						<span>{{ state.detailed.totalScore }}</span>
						<label>总分数{{ state.text }}</label>
					</div>
					<div class="score-item">
						<div>
							<span>{{ state.detailed.calculateAccuracy }}%</span>
							<label>正确率</label>
						</div>
						<div>
							<span>{{ durationTime }}</span>
							<label>总时长</label>
						</div>
						<div>
							<span>{{ state.detailed.correct_number || 0}}</span>
							<label>订正数</label>
						</div>
					</div>
				</div>
				<div>
					<img :src="base64Img.icon1" />
				</div>
			</div>
			<div class="score-list-wrap">
				<div class="title">幼小衔接数学 - {{ categoryItem?.label }}</div>
				<div class="count">
					<span class="n">共{{ state.formulaList.length }}道题</span>
				</div>
				<div class="score-list-content">
					<el-row v-if="state.renderFormula">
						<el-col :span="12" v-for="(item, index) in state.formulaList" :key="item.id">
							<MathFormula :show-result="false" :show-index="false" :type="categoryItem?.type" :index="index" disabled :data="item"/>
						</el-col>
					</el-row>
				</div>
			</div>
		</div>
		<Code />
	</div>
</template>

<script setup>
import { onBeforeMount, reactive, computed, onMounted, nextTick } from "vue"
import { ElRow, ElCol } from "element-plus"
import { useRoute } from "vue-router"
import wx from 'weixin-js-sdk'
import Code from  "@/components/code/index.vue"
import MathFormula from  "@/components/mathFormula/index.vue"
import Mask from  "@/components/loadingMask/index.vue"
import base64Img from "./base64Img"
import { getStaticUrl, calculateAccuracy, secondsToMinutes, calculateScore } from "@/utils"
import { saveShare } from "@/utils/exportImage"
import { getGoodsDetailed, uploadFile, goodsUpdate } from "@/api"
import { useDict } from "@/dict"
window.wx = wx
const mathKindergarten = useDict('mathKindergarten')
const route = useRoute()
const state = reactive({
	query: {
		id: route.query.id,
		face: route.query.face ? getStaticUrl(route.query.face) : getStaticUrl('/app/images/face.png'), 
		name: route.query.name,
		// face:'https://file.web-jshtml.cn/uploads/times/uploads/202412/20241204/7a5aa4196f86ec83d28a8023691336a1.jpeg', 
		// name: 'A总', 
		// id: "169"
	},
	detailed: {},
	formulaList: [],
	renderFormula: false,
	text: '',
	face: ""
})

const categoryItem = computed(() => mathKindergarten.useDictItem(state.detailed.category_id))

const getDetailed = () => {
	getGoodsDetailed({id: state.query.id}).then(res => {
		state.detailed = res.content
		const formula = JSON.parse(res.content.text)
		state.formulaList = formula
		console.log('state.formulaList', formula)
		state.renderFormula = true
		// 正确率
		state.detailed.calculateAccuracy = calculateAccuracy(formula.length, state.detailed.error_number)
		// totalScore
		state.detailed.totalScore = calculateScore(formula.length, state.detailed.error_number) || ''
		nextTick(() => {
			setTimeout(() => {
				createImg()
			}, 2000)
		})
	})
}

const createImg = async () => {
	await nextTick()
	await getBaseimgFile(state.query.face)
	saveShare({ domId: "create-wrap", fileName: '1212' }).then((imageData) => {
		wx.miniProgram.postMessage({
			data: {
				url: imageData
			}
		})
		wx.miniProgram.navigateBack()
		// const formData = new FormData();
		// // 或者，如果你希望将base64转换为blob然后上传：
		// const blob = dataURLtoBlob(imageData); // 将base64转换为blob对象
		// formData.append('files', blob, 'image.png');
		// formData.append('uploadtype', 'share');
		// uploadFile(formData).then((res) => {
		// 	wx.miniProgram.postMessage({
		// 		data: {
		// 			url: res.content.files_path
		// 		}
		// 	})
		// 	wx.miniProgram.navigateBack()
		// })
	})
	.catch(() => {
		wx.miniProgram.navigateBack()
	})
}

const getBaseimgFile = (url) => {
	return new Promise((resolve,reject)=>{ 
		//图片路径转换为Base64↓
		let image = new Image(); // 一定要设置为let，不然图片不显示
		image.setAttribute('crossOrigin', '*'); // 解决跨域问题
		image.src = url + '?time=' + new Date().valueOf();//网络图片路径
		image.onload = () => {
			var canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			var context = canvas.getContext("2d");
			context.drawImage(image, 0, 0, image.width, image.height);
			var quality = 0.8;
			var dataURL = canvas.toDataURL("image/jpeg", quality); 
			// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
			state.face = dataURL
			resolve(); //成功
		};
		
		image.onerror = () => {
			alert('失败')
			reject()
		}
	})
}

const durationTime = computed(() => {
	const str = secondsToMinutes(state.detailed.duration)
	return `${str.minutes}:${str.seconds}`
})


const dataURLtoBlob = (dataurl) => {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while(n--){
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {type:mime});
}
onMounted(() => {
	getDetailed()
})



</script>
<style lang="scss" scoped>
@import "@/styles/var.scss";
#create-wrap {
	background-color: #fff;
}
.score-content {
	background-color: $primary;
	padding-bottom: 4rem;
	overflow: hidden;
	border-radius: 0 0 3rem 3rem;
}
.score-wrap {
	padding: 0 1.5rem 0 2.5rem;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #fff;
	img {
		width: 14rem
	}
}
.total-score {
	font-size: 5rem;
	font-family: "ARLRDBD";
	line-height: 1;
	label {
		margin-top: 0.8rem;
		font-size: 1.2rem;
		display: block;
		opacity: 0.6;
	}
}
.score-item {
	display: flex;
	font-size: 1.7rem;
	font-family: "ARLRDBD";
	line-height: 1;
	margin-top: 1.6rem;
	column-gap: 2rem;
	label {
		margin-top: 0.8rem;
		font-size: 1.2rem;
		display: block;
		opacity: 0.6;
		word-break: break-all;
	}
}
.score-list-wrap {
	border-radius: 3.2rem;
	border: 0.5rem solid #f9d84d;
	background-color: #fff;
	box-shadow: 0 0 1rem 0 rgba(0, 0, 0, .1);
	padding-bottom: 4rem;
	margin: 3rem 2rem;
	.title {
		text-align: center;
		color: $primary;
		padding-top: 2.8rem;
		padding-bottom: 1.6rem;
		font-weight: bold;
	}
	.count {
		position: relative;
		font-size: 1.2rem;
		text-align: center;
		color: $gray-ligh-4;
		z-index: 1;
		margin: 0 2rem 1rem;
		&:before {
			content: '';
			position: absolute;
			border-top: 1px dashed $gray-ligh-4;
			left: 0;
			right: 0;
			top: 50%;
			transform: translateY(-50%) scaleY(0.5);
			z-index: -1;
		}
		span {
			background-color: #fff;
			padding: 0 0.8rem;
		}
	}
}
.score-list-content {
	position: relative;
	&::before, &::after {
		content: '';
		position: absolute;
		width: 1.5rem;
		top: 0;
		bottom: 0;
		z-index: 1;
		background-color: #fff;
	}
	&::before{ left: 0; }
	&::after{ right: 0; }
}
.loading-mask {
	position: fixed;
	z-index: 999999;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	.mask {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		border-radius: 0.8rem;
		background-color: rgba(0, 0, 0, .6);
		padding: 2rem;
		color: #fff;
	}
	.iconfont {
		font-size: 2rem;
	}
	span {
		display: block;
		margin-top: 1rem;
		font-size: 1.4rem;
	}
}

.score-header {
	padding: 2rem;
	display: flex;
	align-items: center;
	.face {
		border: .3rem solid rgba(255, 255, 255, .5);
	}
	.face, img {
		width: 6rem;
		height: 6rem;
		overflow: hidden;
		border-radius: 100px;
	}
	.name {
		color: #fff;
		font-size: 1.8rem;
		margin-left: 1rem;
		line-height: 1rem;
	}
}
.score-header-line {
	margin-bottom: 2rem;
	position: relative;
	border-bottom: .2rem dotted #40d6a9;
	> span {
		position: absolute;
		height: 1.6rem;
		width: 1.6rem;
		border-radius: 100px;
		background-color: #40d6a9;
		top: -0.8rem;
	}
	> span:first-child {
		right: -0.8rem;
	}
	> span:last-child {
		left: -0.8rem;
	}
}
</style>